<template>
  <div style="margin:15px" v-loading="loading">

    <div class="filter-container">
      <div style="float:left;overflow:hidden;display:flex;">
        <div style="float:left;font-size:16px;align-self:center;"> 登录账号：</div>
        <div style="float:left;margin-right:10px">
          <el-input v-model="searchDate.username" type="text" size="small"></el-input>
        </div>
        <div style="float:left;font-size:16px;align-self:center;"> 用户姓名：</div>
        <div style="float:left;margin-right:10px">
          <el-input v-model="searchDate.name" type="text" size="small"></el-input>
        </div>
      </div>
      <div style="float:left;margin-left:20px">
        <el-button class="filter-item" type="primary" icon="el-icon-search" size="small" @click="searchData">搜索</el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="small" icon="el-icon-edit" @click="handleAddClick">添加</el-button>
      </div>
    </div>

    <el-table :data="tableData" border stripe highlight-current-row>
      <el-table-column type="index" :index="rowIndexBegin" width="50"></el-table-column>
      <el-table-column header-align="center" align="left" width="150" prop="username" label="登录账号"></el-table-column>
      <el-table-column header-align="center" align="left" width="120" prop="jobNo" label="用户工号"></el-table-column>
      <el-table-column header-align="center" align="left" width="120" prop="name" label="用户姓名"></el-table-column>
      <el-table-column header-align="center" align="left" width="120" prop="orgName" label="所属组织"></el-table-column>
      <el-table-column header-align="center" align="center" width="100" prop="status" label="用户状态" :formatter="statusFormat"></el-table-column>
      <el-table-column header-align="center" align="center" width="140" prop="mobile" label="联系电话"></el-table-column>
      <el-table-column header-align="center" align="center" width="150" prop="email" label="邮箱"></el-table-column>
      <el-table-column header-align="center" align="center" width="170" prop="lastSignDate" label="最后登录时间"></el-table-column>
      <el-table-column header-align="center" align="center" width="100" prop="" label="操作">
        <template slot-scope="scope">
          <el-button @click.native="handleEditClick(scope.row)" size="small" icon="el-icon-edit">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" width="" prop="" label=""></el-table-column>
    </el-table>

    <div style="margin: 20px;overflow: hidden">
      <div style="text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageCurrent"
          :page-sizes="[5,10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, prev, pager, next, sizes"
          :total="totalSize">
        </el-pagination>
      </div>
    </div>

    <el-dialog title="用户编辑" :visible.sync="dialogFormVisible" :before-close="beforeClose">
      <el-tabs type="border-card">
        <el-tab-pane label="用户信息">
          <el-form :model="form" ref="form" :rules="rules">
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="登录账号：" :label-width="formLabelWidth" prop="username">
                  <el-input v-model="form.username" auto-complete="off" :disabled="!formEdit"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="用户工号：" :label-width="formLabelWidth" prop="jobNo">
                  <el-input v-model="form.jobNo" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="用户姓名：" :label-width="formLabelWidth" prop="name">
                  <el-input v-model="form.name" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="登录密码：" :label-width="formLabelWidth" prop="password">
                  <el-input type="password" v-model="form.password" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="用户状态：" :label-width="formLabelWidth" prop="status">
                  <el-select v-model="form.status" placeholder="请选状态" style="width: 100%;">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="注销" value="8"></el-option>
                    <el-option label="锁定" value="9"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="所属组织：" :label-width="formLabelWidth" prop="orgName">
                  <el-input v-model="form.orgName" auto-complete="off" @focus="dialogTreeOpen"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="身份证号：" :label-width="formLabelWidth">
                  <el-input v-model="form.identity" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="出生日期：" :label-width="formLabelWidth">
                  <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" value-format="yyyy-MM-dd" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="性别：" :label-width="formLabelWidth">
                  <el-radio-group v-model="form.sex">
                    <el-radio :label="'00'">男</el-radio>
                    <el-radio :label="'01'">女</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="" :label-width="formLabelWidth">
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="11">
                <el-form-item label="联系电话：" :label-width="formLabelWidth">
                  <el-input v-model="form.mobile" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col class="line" :span="1">&nbsp;</el-col>
              <el-col :span="11">
                <el-form-item label="Email：" :label-width="formLabelWidth">
                  <el-input v-model="form.email" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-form-item>
              <el-col :span="23">
                <el-form-item label="籍贯：" :label-width="formLabelWidth">
                  <el-input v-model="form.address" auto-complete="off"></el-input>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="角色信息">
          <el-transfer
            v-model="ownRoles"
            :titles="['未分配角色', '已分配角色']"
            :props="{key: 'dbid', label: 'name'}"
            @change="handleChange"
            :data="roles">
          </el-transfer>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormClose">取 消</el-button>
        <el-button type="primary" @click="saveStaffInfo">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="组织结构" :visible.sync="dialogTreeVisible" width="20%" >
      <el-tree
        :data="treeData"
        ref="menuTree"
        :props="defaultProps"
        show-checkbox
        @check="handleCheckChange"
        node-key="dbid"
        :check-strictly="true"
        :expand-on-click-node="true">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectOrg">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {getStaffInfoList, saveStaffInfo, getOwStaffRoleList, getUnStaffRoleList, validateUserName} from 'api/staffinfo';
  import {getRoleInfoList} from 'api/role';
  import {getOrgTree} from 'api/org';
  export default {
    data() {
      let validatorUserName = (rule, value, callback) => {
        if(value !== this.form.old_username) {
          validateUserName(value).then(info => {
            if(info.data === false) {
              callback(new Error(info.msg));
            } else {
              callback();
            }
          });
        } else {
          callback();
        }
      };
      return {
        ownRoles:[],  //左 已分配角色
        roles:[{dbid: 1, name: '111', disabled: false}], //右 未分配角色
        addRoles:[],
        delRoles:[],
        allData: [],//加载数据
        tableData: [],//加载数据
        treeData: [{dbid: '0', name: '组织结构', parentDbid: '', disabled: true, children: []}],
        defaultProps: {label: 'name', children: 'children'},
        totalSize: 0,
        pageSize: 20,//每页显示的条数
        pageCurrent: 1,//第几页
        rowIndexBegin: 1,
        searchDate: {username: '', name: ''},
        loading: false,
        dialogFormVisible: false,  //增加编辑层
        dialogTreeVisible: false,
        formLabelWidth: '100px',
        formEdit: true,
        form: {dbid: '', username: '', old_username: '',orgDbid:'1', orgName:'', name: '', password: '', old_password: '', passwordChange: false, superUser: false,
          status: '0', mobile: '', telephone: '', sex: '00', identity: '', email: '', jobNo: '', address: '', birthday: '', lastSignDate: '',createTime:'',modifyTime:''},
        rules: {
          username: [
            {required: true, message: '请输入登录账号', trigger: 'blur'},
            {validator: validatorUserName, trigger: 'submit'}
          ],
          jobNo: [
            {required: true, message: '请输入用户工号', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入用户姓名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入登录密码', trigger: 'blur'},
//            {min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
          ],
          status: [
            {required: true, message: '请选择用户状态', trigger: 'blur'}
          ]
        }
      }
    },
    methods:{
      mockTableData(){
        let datas = []; //查询结果数据集
        let res = this.addData;
        this.totalSize = res.length;  //确认总数
        let str = (this.pageCurrent - 1) * this.pageSize; //根据当前页数初始化数据
        for(let i = str; i < this.pageSize * this.pageCurrent && i < res.length; i++){  //分页处理
          datas.push(res[i]);
        }
        this.rowIndexBegin = str + 1;
        this.tableData = datas;
      },
      //点击分页前进后退或页数时触发的方法
      handleSizeChange(val){
        this.pageSize = val;
        this.mockTableData()
      },
      //选择每页显示条数触发的方法
      handleCurrentChange(val){
        this.pageCurrent = val;
        this.mockTableData()
      },
      handleAddClick(){
        this.getStaffRoleList(0);
        this.formEdit = true;
        this.dialogFormVisible = true;
      },
      handleEditClick(data){
        this.getStaffRoleList(data.dbid);
        this.formEdit = false;
        this.dialogFormVisible = true;
        this.form = data;
        this.form.old_password = data.password;
        this.form.old_username = data.username;
      },
      statusFormat(row, column, cellValue, index) {
          return cellValue === 0 ? '正常' : cellValue === 8 ? '注销' : '锁定';
      },
      searchData(){
        getStaffInfoList(this.searchDate.username, this.searchDate.name).then(res => {
          console.log(res)
          this.addData = res.data;
          this.mockTableData()
        });
      },
      getStaffRoleList(dbid) {
        this.roles = [];
        this.ownRoles = [];
        this.addRoles = [];
        this.delRoles = [];
        getRoleInfoList('', '', 0, -1).then(info => {
          this.roles =info.data
        });
        getOwStaffRoleList(dbid).then(info => {
          info.data.forEach(d => {
            this.ownRoles.push(d.dbid);
          });
        });
      },
      handleChange(direction, movedKeys, value) {
        if(movedKeys === 'right') {
          value.forEach(dbid => {
            let idx = this.delRoles.indexOf(dbid);
            if(idx !== -1) {
              this.delRoles.splice(idx, 1);
            } else {
              this.addRoles.push(dbid)
            }
          })
        }
        if(movedKeys === 'left') {
          value.forEach(dbid => {
            let idx = this.addRoles.indexOf(dbid);
            if(idx !== -1) {
              this.addRoles.splice(idx, 1);
            } else {
              this.delRoles.push(dbid)
            }
          })
        }
      },
      saveStaffInfo() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.loading = true;
            this.form.addRoles = this.addRoles;
            this.form.delRoles = this.delRoles;
            this.form.passwordChange = this.form.password !== this.form.old_password;
            saveStaffInfo(this.form).then(() => {
              this.loading = false;
              this.dialogFormClose();
              this.searchData();
            }).catch(() => {
              this.loading = false;
            });
          } else {
            this.$message({
              type: 'error',
              message: '请正确填写表单数据!'
            });
            return false;
          }
        });
      },
      dialogFormClose() {
        this.form = {dbid: '', username: '', old_username: '',orgDbid:'1', orgName:'', name: '', password: '', old_password: '', passwordChange: false, superUser: false,
          status: '0', mobile: '', telephone: '', sex: '00', identity: '', email: '', jobNo: '', address: '', birthday: '', lastSignDate: '',createTime:'',modifyTime:''},
        this.dialogFormVisible = false;
      },
      beforeClose(done) {
        this.form = {dbid: '', username: '', old_username: '',orgDbid:'1', orgName:'', name: '', password: '', old_password: '', passwordChange: false, superUser: false,
          status: '0', mobile: '', telephone: '', sex: '00', identity: '', email: '', jobNo: '', address: '', birthday: '', lastSignDate: '',createTime:'',modifyTime:''},
        this.$refs.form.resetFields();
        done();
      },
      dialogTreeOpen() {
        this.treeData = [{dbid: '0', name: '组织结构', parentDbid: '', disabled: true, children: []}];
        this.dialogTreeVisible = true;
        getOrgTree(0).then(res => {
          this.treeData[0].children = res.data;
          let arr = [this.form.orgDbid];
          setTimeout(() => {
            this.$refs.menuTree.setCheckedKeys(arr);
          }, 5);
        });
      },
      handleNodeClick(node) {
        if(!node.children) {
          this.$store.dispatch('orgList', node.dbid).then(() => {
            let d = this.$store.state.org.orgList;
            this.$set(node, 'children', d)
          })
        }
      },
      handleCheckChange(node, check) {
        if(check.checkedKeys.length > 0) {
          let arr = [node.dbid];
          this.$refs.menuTree.setCheckedKeys(arr);
        }
      },
      selectOrg() {
        let nodes = this.$refs.menuTree.getCheckedNodes();
        if(nodes.length > 0) {
          this.form.orgDbid = nodes[0].dbid;
          this.form.orgName= nodes[0].name;
        }
        this.dialogTreeVisible = false;
      }
    },
    created(){
      this.searchData();
    },
    mounted(){

    },
    computed:{

    }
  }
</script>
